package com.webull.information.center.carwler.common.util.news;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.TimeZone;
import java.util.function.Supplier;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.webull.framework.fm.FreeMarkerService;
import com.webull.framework.util.UtilDate;
import com.webull.information.center.carwler.common.model.NewsInformation;
import com.webull.information.center.common.constants.Constants;
import com.webull.information.client.model.News;

/**
 * 新闻生成静态网页操作合集
 *
 * @author shimingjun
 * @version 1.0
 * @date 2016年8月17日 下午8:40:03
 * @since JDK 1.8
 */
@Component
public class NewsWrapperUtil {
    private final Logger logger = LogManager.getLogger(getClass());
    private @Autowired
    FreeMarkerService fmService;



    /**
	 * 扩展
	 * 
	 * @param info0
	 * @param news
	 * @return
	 */
	public Boolean needToUpdate2(NewsInformation info0, News news) {
		if (info0.isForceReview()) {
			return true;
		} else if (ObjectUtils.compare(info0.getHomePage(), news.getHomePage()) > 0) {
			return true;
		} else if (ObjectUtils.compare(info0.getNewsTime(), news.getNewsTime()) > 0) {
			return true;
		}
		// else if (News.SiteType.PIRORIT.equals(news.getSiteType())) {//
		// 聚合类的文件是公共html，不需要更新
		// return false;
		// }
		return false;
	}

    /**
     * 生成新闻静态HTML文件以及版本号
     *
     * @param info
     * @return HtmlResult
     * @since 0.1.0
     */
    @SuppressWarnings({"rawtypes",})
    public HtmlResult newsHtmlFile(NewsInformation info) {
        try {
            String[] infos = screenNewsTemplateAndVer(info);
            String templateFile = infos[0];

            String version = StringUtils.isNotBlank(info.getContent()) ? "1" : "0";

            Map model = generateInfoModel(templateFile, info);
            if (StringUtils.isBlank(templateFile) || model == null) {
                logger.warn("NewsWrapperUtil newsHtmlFile screen or generate is null{}",
                        objectMapper.convertValue(info, HashMap.class));
                return null;
            }
            return new HtmlResult(version, fmService.process(templateFile, model));
            // fmService.process(templateFile, model);
        } catch (Exception e) {
            logger.error("newsHtmlFile error:{},{}", objectMapper.convertValue(info, HashMap.class), e);
            return null;
        }
    }

    /**
     * 查找模板和页面版本号
     *
     * @param info
     * @return
     * @since 0.1.0
     */
    private String[] screenNewsTemplateAndVer(NewsInformation info) {
        return new String[]{news_templateFile, "1"};
    }

    /**
     * 生成model
     *
     * @param templateFile
     * @param info
     * @return
     * @since 0.1.0
     */

    @SuppressWarnings({"rawtypes", "unchecked"})
    private Map generateInfoModel(String templateFile, NewsInformation info) {
        String lang = info.getLanguage();
        // if (StringUtils.isBlank(info.getPushTime())) {
        TimeZone zzz = Optional.ofNullable(info.getNewsTimeZone()).orElse(TimeZone.getDefault());
        if (Constants.lang_zh.equals(lang))
            info.setPushTime(UtilDate.format(info.getNewsTime(), Locale.US, zzz, "yyyy-MM-dd HH:mm"));
        else
            info.setPushTime(UtilDate.format(info.getNewsTime(), Locale.US, zzz, "MMM dd, yyyy hh:mm a z"));//// MMM
        //// DD
        //// YYYY,HH:MM
        //// AM/PM
        //// TMZ
        // }

        Map model = objectMapper.convertValue(info, HashMap.class);
        model.put("newsMilliTime", info.getNewsTime().getTime()+"");
        // 判断是否有效http的url
		if (isSpecCollect(info.getCollectSource())
				|| (info.getHomePage() != null && info.getHomePage() >= News.HomeType.top)) {
            model.put("good_url", "no");
        } else {
            model.put("good_url", "good");
        }

        String lang_ = "";
        String rela_stock = "Related";
        if (StringUtils.equals(Constants.lang_zh, lang)) {
            lang_ = "查看原文";
            rela_stock = "相关";
        } else if (StringUtils.equals(Constants.lang_zh_hant, lang)) {
            lang_ = "查看原文";
            rela_stock = "相關";
            // html_title = "新聞詳情";
        } else {
            lang_ = "Read more";
            rela_stock = "Related";
            // html_title = "News detail";
        }
        model.put("html_title", info.getTitle());
        model.put("read_more", lang_);
        model.put("rela_stock", rela_stock);
        model.put("url_md5", info.getUrlMd5());

        if (info.getArticleClass() != null) {
            model.put("articleClass", info.getArticleClass().getVal());
        }
        return model;
    }

    private static String[] specialSources = new String[]{News.CollectSource.hengSheng,
			News.CollectSource.wallStreet,
            News.CollectSource.reutersGuide};

    public boolean isSpecCollect(String collectSource) {
        return ArrayUtils.contains(specialSources, collectSource);
    }

    private final static String news_templateFile = "news.html";
    private final static ObjectMapper objectMapper = new Supplier<ObjectMapper>() {
        @Override
        public ObjectMapper get() {
            return new ObjectMapper().setSerializationInclusion(Include.NON_NULL)
                    .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
        }
    }.get();

    /**
     * 新闻HTML生成结果
     *
     * @author shimingjun
     * @version 1.0
     * @date 2016年8月18日 上午11:37:00
     * @since JDK 1.8
     */
    public static class HtmlResult {
        /**
         * HTML静态文件版本号
         */
        private String version;
        /**
         * HTML静态文件
         */
        private String html;

        public HtmlResult(String version, String html) {

            this.version = version;
            this.html = html;
        }

        public String getVersion() {
            return version;
        }

        public String getHtml() {
            return html;
        }

    }

    public static void main(String[] args) {

        boolean a = "(( gdynia.news roomtho mson@reuters.com; +48 58 772 0920;)))"
                .matches("\\({2}[^(](|\\S|\\s){1,}@(\\S|\\s){1,}[^)]\\){2}");
        System.out.println(a);
    }
}
